package com.hqyj.springbootdemo01.common.component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hqyj.springbootdemo01.user.dto.UserInfo;
import com.hqyj.springbootdemo01.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author sdx2009
 * @package com.hqyj.springbootdemo01.common.component
 * @date 2022/8/29 15:58
 */
@Component
public class JwtComponent {
    //    从yml文件获取配置项
    @Value("#{${system.expireTime}}")
    private Map<String, Long> expireTime;

    /**
     * JWT token生成
     *
     * @param userName
     * @param password
     * @param expireType
     * @return
     */
    public String sign(String userName, String password, String expireType) {
        try {
            // 生成算法
            Algorithm algorithm = Algorithm.HMAC256(userName + password);

            // 过期时间
            Date expireDate = new Date(System.currentTimeMillis() + expireTime.get(expireType));
            //生成JWT token
            return JWT.create().withClaim("userName", userName).withExpiresAt(expireDate)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * token验证
     *
     * @param token
     * @param userName
     * @param password
     * @return
     */
    public boolean verify(String token, String userName, String password) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(userName + password);
            JWTVerifier jwtVerifier = JWT.require(algorithm).withClaim("userName", userName)
                    .build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从token中获取userName
     *
     * @param token
     * @return
     */
    public String getUserNameByToken(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("userName").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从token中获取过期时间
     *
     * @param token
     * @return
     */
    public Date getExpireTimeByToken(String token) {
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getExpiresAt();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}
